package main

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"github.com/nacos-group/nacos-sdk-go/v2/inner/uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"mxshop-api/minio-web/global"
	"mxshop-api/minio-web/initialize"
	"mxshop-api/minio-web/utils"
	"mxshop-api/minio-web/utils/register/consul"
	customerValidator "mxshop-api/user-web/validator"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	//1.初始化日志
	initialize.InitLogger()
	//2.初始化配置文件
	initialize.InitConfig()
	//3.初始化Routers
	Router := initialize.Routers()
	//4. 初始化 翻译
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}
	viper.AutomaticEnv() // 自动从环境变量获取值
	//如果是本地开发环境端口号固定,线上环境启动获取端口号
	debug := viper.GetBool(global.ServerConfig.Dev)
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port //更改端口号
		}
	}

	//注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", customerValidator.ValidateMobile)
		//翻译自定义异常
		_ = v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0} 非法的手机号码", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}

	consulInfo := global.ServerConfig.ConsulInfo
	serviceId, _ := uuid.NewV4()
	srvId := fmt.Sprintf("%s", serviceId)

	registerClient := consul.NewRegistryClient(consulInfo.Host, consulInfo.Port)
	err := registerClient.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, srvId)
	if err != nil {
		zap.S().Panic("服务注册失败：", err.Error())
	}
	//全局日志
	zap.S().Debugf("启动服务器, 端口: %d", global.ServerConfig.Port)

	go func() {
		if err := Router.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
			zap.S().Panic("启动失败:", err.Error())
		}
	}()
	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = registerClient.DeRegister(srvId); err != nil {
		zap.S().Info("注销失败:", err.Error())
	} else {
		zap.S().Info("注销成功")
	}
}
